package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.ResultVo;
import com.qf.User;
import com.qf.mapper.UserMapper;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class UserService implements IUserService{
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public ResultVo insertUser(User user) {
        User selectByUserName = userMapper.selectByUserName(user.getUserAccount());
        if(selectByUserName == null){
            int i = userMapper.insert(user);
            if(i == 1){
                return  new ResultVo(200,"注册成功！");
            }else {
                return new ResultVo(500,"注册失败！");
            }
        }
        return new ResultVo(500,"账户已存在！");
    }

    @Override
    public ResultVo selectUser(User user) {
        if(!StringUtils.isEmpty(user.getUserAccount())){
            if(!StringUtils.isEmpty(user.getUserPwd())){
                User user1 = userMapper.selectByUserName(user.getUserAccount());
                
                if(user.getUserPwd().equals(user1.getUserPwd())){
                    user.setUserId(user1.getUserId());
                    String token = getToken(user1);
                    return new ResultVo(200,"登录成功！",token);
                }
                return new ResultVo(500,"账号或密码有误！");
            }
        }
        
        return new ResultVo(500,"账号或密码不能为空！");
    }

    @Override
    public ResultVo updateUser(User user) {

        int i = userMapper.updateById(user);
        if(i == 1){
            return  new ResultVo(200,"保存成功！");
        }else {
            return new ResultVo(500,"保存失败！");
        }
    }
    
    @Override
    public String getToken(User user){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        JwtBuilder builder = Jwts.builder();
        String token = builder.setSubject(user.getUserAccount())                 //主题，就是token中携带的数据
                .setIssuedAt(new Date())                            //设置token的生成时间
                .setId(user.getUserId()+"")               //设置用户id为token  id
                .setClaims(map)                                     //map中可以存放用户的角色权限信息
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) //设置过期时间
                .signWith(SignatureAlgorithm.HS256, "QIANfeng6666")     //设置加密方式和加密密码
                .compact();
        System.out.println(token);
        return token;
    }

    @Override
    public User selectUserByAccount(String userAccount) {
        User user = userMapper.selectByUserName(userAccount);
        
        return user;
    }

}
